package com.brotherly.mpgp;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pl.polidea.coverflow.CoverFlow;
import pl.polidea.coverflow.ReflectingImageAdapter;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.brotherly.framework.BaseActivity;
import com.brotherly.framework.app.BaseApplication;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.mpgp.remoteinterface.RemoteServerService;
import com.brotherly.mpgp.remoteinterface.RemoteServerWatcher;
import com.brotherly.mpgp.util.GameManagerUtil;
import com.brotherly.mpgp.view.DownLoadButton;
import com.brotherly.mpgp.view.ResourceImageAdapter;
import com.brotherly.mpgp.view.UpdateFreshListView;
import com.brotherly.mpgp.view.UpdateFreshListView.OnRefreshListener;
import com.brotherly.util.InternetResourceCache;
import com.brotherly.util.downloader.DownLoaderUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

public class MainActivity extends BaseActivity implements OnClickListener, OnTouchListener
{
    private class CheatsListAdapter extends BaseAdapter implements OnItemClickListener
    {
        private boolean mIsShowPic = true;

        private List<JSONObject> mArticles;

        private LayoutInflater mInflater;

        public CheatsListAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount()
        {
            return mArticles == null ? 0 : mArticles.size();
        }

        @Override
        public Object getItem(int position)
        {
            return mArticles.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = (ViewGroup) mInflater.inflate(R.layout.article_list_item, null);
            }
            if (position % 2 == 0)
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_1);
            } else
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_2);
            }
            try
            {
                JSONObject item = (JSONObject) getItem(position);
                String type = item.getString("type");

                TextView title = (TextView) convertView.findViewById(R.id.tv_article_list_item_title);
                title.setText(item.getString("title"));
                View typeView = convertView.findViewById(R.id.v_type);
                Button getAccount = (Button) convertView.findViewById(R.id.btn_get_account);
                JSONObject info = null;
                JSONObject action = null;
                if (item.has("info"))
                {
                    info = item.getJSONObject("info");
                    if (info.has("action"))
                    {
                        JSONArray actions = info.getJSONArray("action");
                        if (actions.length() > 0)
                        {
                            action = actions.getJSONObject(0);
                        }
                    }
                }

                ImageView imageview = (ImageView) convertView.findViewById(R.id.iv_article_list_item_image);
                // imageview.setVisibility(View.GONE);
                if (mIsShowPic)
                {
                    imageview.setVisibility(View.VISIBLE);
                    loadArticleFirstImage(item, imageview);
                    title.setLines(2);
                } else
                {
                    imageview.setVisibility(View.GONE);
                    title.setLines(1);
                }
                if (action != null)
                {
                    getAccount.setVisibility(View.VISIBLE);
                } else
                {
                    getAccount.setVisibility(View.GONE);
                }
                if ("course".equals(type))
                {
                    typeView.setBackgroundColor(0xff7ac3c9);
                } else
                {
                    typeView.setBackgroundColor(0xfffc7a7e);
                }

                TextView content = (TextView) convertView.findViewById(R.id.tv_article_content);
                if (mIsShowPic)
                {
                    content.setVisibility(View.GONE);
                } else
                {
                    content.setVisibility(View.VISIBLE);
                    String contentStr = item.getString("content");
                    JSONArray contents = new JSONArray(contentStr);
                    for (int i = 0; i < contents.length(); i++)
                    {
                        if ("para".equals(contents.getJSONObject(i).getString("type")))
                        {
                            content.setText(contents.getJSONObject(i).getString("content"));
                        }
                    }
                }

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return convertView;
        }

        @Override
        public void notifyDataSetChanged()
        {
            mArticles = new ArrayList<JSONObject>(GameManagerUtil.ArticlesList);
            SharedPreferences sp = getSharedPreferences("Setting", MODE_PRIVATE);
            mIsShowPic = sp.getBoolean("isShowPic", false);
            super.notifyDataSetChanged();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent intent = new Intent(MainActivity.this, ArticleActivity.class);
            intent.putExtra("isShowRelatedGame", true);
            intent.putExtra("Articles", mArticles.toString());
            intent.putExtra("Index", position - 1);
            startActivity(intent);
        }
    }

    class GameListAdapter extends BaseAdapter implements OnItemClickListener
    {
        private HashMap<String, ApplicationInfo> mApplicationInfos;
        private Context mContext;
        private List<JSONObject> mGameInfos;
        private LayoutInflater mInflater;

        public GameListAdapter(Context context)
        {
            super();
            this.mContext = context;
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount()
        {
            return mGameInfos == null ? 0 : mGameInfos.size();
        }

        @Override
        public Object getItem(int position)
        {

            return mGameInfos.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = (ViewGroup) mInflater.inflate(R.layout.main_game_list_item, null);
            }
            if (position % 2 == 0)
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_1);
            } else
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_2);
            }
            PackageManager packageManager = mContext.getPackageManager();
            JSONObject gameinfo = (JSONObject) getItem(position);
            try
            {
                String packageName = gameinfo.getString("packageName");
                String name = gameinfo.getString("name");
                ApplicationInfo applicationInfo = mApplicationInfos.get(packageName);
                if (applicationInfo == null)
                {
                    return convertView;
                }
                Drawable icon = packageManager.getApplicationIcon(applicationInfo);
                ((TextView) convertView.findViewById(R.id.tv_game_name)).setText(name);
                ((ImageView) convertView.findViewById(R.id.iv_game_list_item_icon)).setImageDrawable(icon);
                JSONObject info = gameinfo.getJSONObject("info");
                String courses = "0";
                if (!info.isNull("courses"))
                {
                    courses = info.getString("courses");
                }
                ((TextView) convertView.findViewById(R.id.tv_strategy_count)).setText(courses);
                String promotions = "0";
                if (!info.isNull("promotions"))
                {
                    promotions = info.getString("promotions");
                }
                ((TextView) convertView.findViewById(R.id.tv_campaign_count)).setText(promotions);
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
            convertView.setTag(gameinfo);
            return convertView;
        }

        @Override
        public void notifyDataSetChanged()
        {
            this.mApplicationInfos = new HashMap<String, ApplicationInfo>(GameManagerUtil.ApplicationInfos);
            this.mGameInfos = new ArrayList<JSONObject>(GameManagerUtil.GameInfos);
            super.notifyDataSetChanged();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            try
            {
                JSONObject item = (JSONObject) getItem(position - 1);
                Intent intent = new Intent(MainActivity.this, ArticleListActiviy.class);
                intent.putExtra("packageName", item.getString("packageName"));
                intent.putExtra("GameName", item.getString("name"));
                MobclickAgent.onEvent(MainActivity.this, "ShowArticleList");
                MainActivity.this.startActivity(intent);
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    }

    private class MainPagerAdapter extends PagerAdapter implements OnPageChangeListener {

        private ArrayList<LinearLayout> mViews = null;

        public MainPagerAdapter(ArrayList<LinearLayout> views)
        {
            this.mViews = views;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView(mViews.get(position));
        }

        @Override
        public int getCount()
        {
            return mViews.size();
        }

        @Override
        public float getPageWidth(int position)
        {
            if (position == mViews.size() - 1)
            {
                return SetupWidthGene;
            } else
            {
                return super.getPageWidth(position);
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            ViewGroup.LayoutParams lp = null;
            lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);

            container.addView(mViews.get(position), lp);
            return mViews.get(position);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1)
        {
            return arg0 == arg1;
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
        {
            if (position == mViews.size() - 2)
            {
                mMenuBar.scrollTo(positionOffsetPixels, 0);
                int scrollx = -displayWidth
                        + (int) ((positionOffset) * displayWidth + (100 * (SetupWidthGene - positionOffset)));
                mSetupLayout.scrollTo(scrollx, 0);
            } else
            {
                mMenuBar.scrollTo(0, 0);
                mSetupLayout.scrollTo(-displayWidth + 100, 0);
            }
        }

        @Override
        public void onPageScrollStateChanged(int status)
        {
            if (status == ViewPager.SCROLL_STATE_IDLE || status == ViewPager.SCROLL_STATE_SETTLING)
            {
                int index = mViewPager.getCurrentItem();
                if (index != -1)
                {
                    if (index < mViews.size() - 1)
                    {
                        updateMenuStatus(index);
                    }
                }
            }
        }

        @Override
        public void onPageSelected(int position)
        {
            if (position == 1 && mCheatsListView.isOnPull())
            {
                mCheatsListView.revertState();
            } else if (position != 2 && mRecommendListView.isOnPull())
            {
                mRecommendListView.revertState();
            }

            if (position == 1)
            {
                mCheatsListAdapter.notifyDataSetChanged();
            }
        }
    }

    class RecommendListAdapter extends BaseAdapter implements OnItemClickListener
    {
        @SuppressWarnings("unused")
        private Context mContext;
        private List<JSONObject> mGameRecommends;
        private LayoutInflater mInflater;

        public RecommendListAdapter(Context context)
        {
            super();
            this.mContext = context;
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount()
        {
            return mGameRecommends == null ? 0 : mGameRecommends.size();

        }

        @Override
        public Object getItem(int position)
        {
            if (position < mGameRecommends.size())
            {
                return mGameRecommends.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = (ViewGroup) mInflater.inflate(R.layout.main_recommend_list_item, null);
            }

            JSONObject gameinfo = (JSONObject) getItem(position);
            try
            {
                boolean isDataUpdate = true;
                if (convertView.getTag() == gameinfo)
                {
                    isDataUpdate = false;
                }
                if (isDataUpdate)
                    if (position % 2 == 0)
                    {
                        convertView.setBackgroundResource(R.drawable.list_item_background_1);
                    } else
                    {
                        convertView.setBackgroundResource(R.drawable.list_item_background_2);
                    }

                String name = gameinfo.getString("name");
                if (isDataUpdate)
                {
                    if (gameinfo.has("info"))
                    {
                        JSONObject info = gameinfo.getJSONObject("info");
                        if (info.has("players"))
                        {
                            ((TextView) convertView.findViewById(R.id.btn_game_tag_2)).setText("" + info.getInt("players"));
                        }
                        if (info.has("size"))
                        {
                            int size = info.getInt("size");
                            String fileSizeStr = mFileSizeFomat.format(size / 1024d / 1024d);
                            ((TextView) convertView.findViewById(R.id.btn_game_tag_1)).setText(fileSizeStr);
                        }
                    }
                    ((TextView) convertView.findViewById(R.id.tv_game_list_item_gamename)).setText(name);
                }

                ImageView icon = ((ImageView) convertView.findViewById(R.id.iv_game_list_item_icon));
                if (isDataUpdate || (icon.getTag() != null && !(Boolean) icon.getTag()))
                {

                    int id = gameinfo.getInt("id");

                    String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("games/blob?key=image&gameref=")
                            .append(id).toString();

                    if (imageViewLoadInternetResource(icon, imageurl, R.drawable.grap_icon))
                    {
                        icon.setTag(true);
                    } else
                    {
                        icon.setTag(false);
                    }
                }

                String packages = null;
                int fileSize = 0;
                if (gameinfo.has("info"))
                {
                    JSONObject info = gameinfo.getJSONObject("info");
                    try
                    {
                        packages = info.getString("package");
                        fileSize = info.getInt("size");
                    }
                    catch (JSONException e)
                    {
                        Log.d("TAG", "info not packages ");
                    }
                }
                int gameId = gameinfo.getInt("id");
                DownLoadButton dlButton = (DownLoadButton) convertView.findViewById(R.id.dl_button);
                if (packages == null)
                {
                    dlButton.setVisibility(View.INVISIBLE);
                }
                else
                {
                    dlButton.setVisibility(View.VISIBLE);
                    dlButton.setFileSize(fileSize);
                    dlButton.setKey(gameId, name);
                    DownloadEvent event = mDownloadEvents.get(dlButton.getUrl());
                    if (event != null)
                    {
                        if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Info))
                        {
                            int param1 = (Integer) event.param1;
                            if (1 == param1)
                            {
                                JSONObject json = (JSONObject) event.param2;
                                dlButton.setDownLoading();
                                dlButton.setFileSize(json.getInt("fileSize"));
                                dlButton.setComplete(json.getInt("compelete"));
                                dlButton.showProgress();

                                Log.d(dlButton.getUrl(), "Param = 1 FileSize : " + dlButton.getFileSize()
                                        + "    Complete:" + dlButton.getComplete());
                                if (dlButton.getFileSize() <= dlButton.getComplete())
                                {
                                    Log.d(dlButton.getUrl(), "下载完成！");
                                    dlButton.stopDownload();
                                    dlButton.setStatusText();
                                    mDownloadEvents.remove(dlButton.getUrl());
                                }
                            } else if (0 == param1)
                            {
                                dlButton.setPause();
                                dlButton.invalidate();
                            }
                        } else if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Pause))
                        {
                            dlButton.setPause();
                            dlButton.invalidate();
                        } else if (event.id.equals(DownLoaderUtil.Activity_Event_FileDownload_Start))
                        {
                            dlButton.setDownLoading();
                            dlButton.setStatusText();
                        }
                    } else
                    {
                        dlButton.checkLocalFile();
                    }
                }

            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
            convertView.setTag(gameinfo);

            return convertView;
        }

        @Override
        public void notifyDataSetChanged()
        {
            this.mGameRecommends = new ArrayList<JSONObject>(GameManagerUtil.GameRecommends);
            super.notifyDataSetChanged();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            try
            {
                JSONObject item = (JSONObject) getItem(position - 1);
                if (item != null)
                {
                    Intent intent = new Intent(MainActivity.this, GameDetailActivity.class);
                    int gameref = item.getInt("id");
                    intent.putExtra("gameref", gameref);
                    if (item.has("identifiers"))
                    {
                        JSONArray identifiers = item.getJSONArray("identifiers");
                        if (identifiers.length() > 0)
                        {
                            intent.putExtra("packageName", identifiers.getString(0));
                            MainActivity.this.startActivity(intent);
                        }
                    }
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static final int ACTIVITY_TYPE_ABOUT_APP = 1;

    private static final int ACTIVITY_TYPE_HELP = 2;

    private static final int ACTIVITY_TYPE_SUGGESTION = 0;

    private static final int COUNT_PER_PAGE = 10;
    public static final float SetupWidthGene = 0.8f;
    public static final int[] Tag_Backgrounds = {
            R.drawable.tag_1_background, R.drawable.tag_2_background, R.drawable.tag_3_background, R.drawable.tag_4_background
    };

    private boolean isCreate = true;
    private View mAboutAppBtn = null;
    private Button mCategory;
    private LinearLayout mCategoryLayout;
    private Button mCheats;

    private LinearLayout mCheatsLayout;

    private CheatsListAdapter mCheatsListAdapter;
    private UpdateFreshListView mCheatsListView;
    private boolean isCheatsClear = true;
    private Button mGame;

    private LinearLayout mGameLayout;
    private GameListAdapter mGameListAdapter;
    private UpdateFreshListView mGameListView;
    private View mHelpBtn = null;
    private View mClearBtn = null;
    private CheckBox mIsShowPic = null;
    private HashMap<String, DownloadEvent> mDownloadEvents = new HashMap<String, DownloadEvent>();

    float mLastDownX = 0;

    private MainPagerAdapter mMainPagerAdapter;

    private RelativeLayout mMenuBar;
    private Button mRecommend;
    private LinearLayout mRecommendLayout;
    private RecommendListAdapter mRecommendListAdapter;
    private UpdateFreshListView mRecommendListView;

    DecimalFormat mFileSizeFomat = new DecimalFormat("0.00M");

    private UpdateFreshListView.OnRefreshListener mRefreshListener = new OnRefreshListener()
    {

        @Override
        public void onLoadMore(UpdateFreshListView listview)
        {
            if (listview == mRecommendListView)
            {} else if (listview == mCheatsListView)
            {
                isCheatsClear = false;
                int index = GameManagerUtil.ArticlesList.size() / COUNT_PER_PAGE;
                gameArticles(index, COUNT_PER_PAGE);
            }
        }

        @Override
        public void onRefresh(UpdateFreshListView listview)
        {
            if (listview == mRecommendListView)
            {
                gameRank();
            } else if (listview == mCheatsListView)
            {

                isCheatsClear = true;
                gameArticles(0, COUNT_PER_PAGE);
            }
        }
    };
    private Button mSetup;
    private RelativeLayout mSetupLayout;
    private RelativeLayout mStartScreen;
    private Button mSuggestion;

    private ViewPager mViewPager;

    private void appInitDownLoad()
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        ArrayList<String> types = new ArrayList<String>();
        types.add("promotion");
        types.add("course");

        ArrayList<String> identifiers = new ArrayList<String>();
        for (String key : GameManagerUtil.ApplicationInfos.keySet())
        {
            identifiers.add(key);
        }
        rss.initDownLoad(types, identifiers, "热门排行", 0, 20);
    }

    private void createTagsShow()
    {
        Random random = new Random(Tag_Backgrounds.length);
        LinearLayout container = (LinearLayout) mCategoryLayout.findViewById(R.id.tags_container);
        container.removeAllViews();
        List<String> tags = new ArrayList<String>(GameManagerUtil.GameTags);
        int count = tags.size();
        int row = count % 4 == 0 ? count / 4 : count / 4 + 1;
        int col = 4;
        for (int r = 0; r < row; r++)
        {
            LinearLayout cc = new LinearLayout(this);
            LinearLayout.LayoutParams clp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            cc.setLayoutParams(clp);
            if (r == 0)
                clp.topMargin = converToPx(10);
            else
                clp.topMargin = converToPx(5);
            clp.bottomMargin = converToPx(5);
            for (int c = 0; c < col; c++)
            {
                int index = r * col + c;
                String tag = "";
                @SuppressWarnings("unused")
                int total = 0;
                if (index < tags.size())
                {
                    try
                    {
                        String json = tags.get(index);
                        JSONObject j = new JSONObject(json);
                        tag = j.getString("tag");
                        total = j.getInt("count");
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                final TextView t = new TextView(this);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT, 1);
                if (tag != null && !tag.trim().equals(""))
                {
                    if (c == 0)
                        lp.leftMargin = converToPx(5);
                    lp.rightMargin = converToPx(5);
                    if (c == 1)
                        lp.rightMargin = converToPx(5);
                    if (c == 2)
                        lp.rightMargin = converToPx(5);
                    if (c == 3)
                        lp.rightMargin = converToPx(5);

                    t.setTextColor(Color.WHITE);
                    t.setGravity(Gravity.CENTER);
                    t.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                    t.setBackgroundResource(Tag_Backgrounds[random.nextInt(Tag_Backgrounds.length)]);
                    t.setText(tag);
                    int height = converToPx(55);
                    t.setHeight(height);
                    t.setPadding(0, 0, 0, 0);
                }
                t.setLayoutParams(lp);
                t.setOnClickListener(new OnClickListener()
                {

                    @Override
                    public void onClick(View v)
                    {
                        Intent i = new Intent(MainActivity.this, GameListActivity.class);
                        i.putExtra("tag", t.getText());
                        startActivity(i);
                    }
                });
                cc.addView(t);
            }
            container.addView(cc);
        }
    }

    private void gameArticles(int index, int count)
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        rss.gameArticles(null, index, count);
    }

    public void gameIdentifier()
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        rss.gameIdentifier();
    }

    public void gameRank()
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        String rankName = "热门排行";
        rss.gameRank(rankName);
    }

    public void gameRankNames()
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        rss.gameRankNames();
    }

    public void gameTags()
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        rss.gameTags();
    }

    public void loadArticleFirstImage(JSONObject article, ImageView imageview)
    {
        try
        {
            JSONArray contents = new JSONArray(article.getString("content"));
            boolean isHaveImage = false;
            for (int i = 0; i < contents.length(); i++)
            {
                JSONObject content = contents.getJSONObject(i);
                String type = content.getString("type");
                if ("image".equals(type))
                {
                    String key = content.getString("content");
                    int id = article.getJSONObject("info").getJSONArray(key).getJSONObject(0).getInt("id");
                    String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("articles/blob?ref=")
                            .append(id).toString();
                    imageViewLoadInternetResource(imageview, imageurl, 0);

                    imageview.setTag(imageurl);
                    isHaveImage = true;
                    break;
                }
            }
            if (!isHaveImage)
            {
                imageview.setImageDrawable(new ColorDrawable(0x00000000));
            }
        }
        catch (Exception e)
        {}
    }

    @Override
    public void onAllReady()
    {
        mDownloadEvents.clear();
        if (isCreate)
        {
            GameManagerUtil.loadPackageInfo(MainActivity.this, null);
            appInitDownLoad();
        } else
        {
            mRecommendListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v)
    {
        if (v == mGame)
        {
            mViewPager.setCurrentItem(0, true);
        } else if (v == mCheats)
        {
            mViewPager.setCurrentItem(1, true);
        } else if (v == mRecommend)
        {
            mViewPager.setCurrentItem(2, true);
        } else if (v == mCategory)
        {
            mViewPager.setCurrentItem(3, true);
        } else if (v == mSetup)
        {
            if (mViewPager.getCurrentItem() == 4)
            {
                mViewPager.setCurrentItem(3, true);
            } else
            {
                mViewPager.setCurrentItem(4, true);
            }
        } else if (v == mSuggestion)
        {
            startActivity(ACTIVITY_TYPE_SUGGESTION);
        } else if (v == mAboutAppBtn)
        {
            startActivity(ACTIVITY_TYPE_ABOUT_APP);
        } else if (v == mHelpBtn)
        {
            startActivity(ACTIVITY_TYPE_HELP);
        } else if (v == mClearBtn)
        {
            showClearDailog();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // com.umeng.common.Log.LOG = true;

        super.onCreate(savedInstanceState);
        UmengUpdateAgent.update(this);
        setContentView(R.layout.activity_main);
        mViewPager = (ViewPager) findViewById(R.id.vp_main);
        mMenuBar = (RelativeLayout) findViewById(R.id.rl_menubar);

        ArrayList<LinearLayout> views = new ArrayList<LinearLayout>();
        LayoutInflater mInflater = LayoutInflater.from(this);
        mGameLayout = (LinearLayout) mInflater.inflate(R.layout.main_game_list_viewpager_item, null);
        mGameListView = (UpdateFreshListView) mGameLayout.findViewById(R.id.lv_game);
        mGameListView.setIsShowLoadMoreFooter(false);
        mGameListAdapter = new GameListAdapter(this);
        mGameListView.setAdapter(mGameListAdapter);
        mGameListView.setOnItemClickListener(mGameListAdapter);
        views.add(mGameLayout);

        mCheatsLayout = (LinearLayout) mInflater.inflate(R.layout.main_cheats_list_viewpager_item, null);
        mCheatsListView = (UpdateFreshListView) mCheatsLayout.findViewById(R.id.lv_cheats);
        mCheatsListAdapter = new CheatsListAdapter(this);
        mCheatsListView.setAdapter(mCheatsListAdapter);
        mCheatsListView.setIsShowLoadMoreFooter(false);
        mCheatsListView.setOnItemClickListener(mCheatsListAdapter);
        mCheatsListView.setOnRefreshListener(mRefreshListener);
        views.add(mCheatsLayout);

        mRecommendLayout = (LinearLayout) mInflater.inflate(R.layout.main_recommend_list_viewpager_item, null);
        mRecommendListView = (UpdateFreshListView) mRecommendLayout.findViewById(R.id.lv_recommend);
        mRecommendListAdapter = new RecommendListAdapter(this);
        mRecommendListView.setAdapter(mRecommendListAdapter);
        mRecommendListView.setOnItemClickListener(mRecommendListAdapter);
        mRecommendListView.setOnRefreshListener(mRefreshListener);
        mRecommendListView.setIsShowLoadMoreFooter(false);

        views.add(mRecommendLayout);

        mCategoryLayout = (LinearLayout) mInflater.inflate(R.layout.main_category_list_viewpager_item, null);
        views.add(mCategoryLayout);

        LinearLayout ll = (LinearLayout) mInflater.inflate(R.layout.main_blank_list_viewpager_item, null);
        ll.setOnTouchListener(this);
        views.add(ll);

        mMainPagerAdapter = new MainPagerAdapter(views);
        mViewPager.setAdapter(mMainPagerAdapter);
        mViewPager.setOnPageChangeListener(mMainPagerAdapter);

        mSetupLayout = (RelativeLayout) findViewById(R.id.ll_setup);
        mSuggestion = (Button) mSetupLayout.findViewById(R.id.but_suggestion);
        mSuggestion.setOnClickListener(this);

        mAboutAppBtn = mSetupLayout.findViewById(R.id.but_about);
        mAboutAppBtn.setOnClickListener(this);

        mHelpBtn = mSetupLayout.findViewById(R.id.but_help);
        mHelpBtn.setOnClickListener(this);

        mClearBtn = mSetupLayout.findViewById(R.id.but_data_clear);
        mClearBtn.setOnClickListener(this);

        mIsShowPic = (CheckBox) mSetupLayout.findViewById(R.id.pic_off_on);
        SharedPreferences sp = getSharedPreferences("Setting", MODE_PRIVATE);
        boolean isShowPic = sp.getBoolean("isShowPic", false);
        mIsShowPic.setChecked(isShowPic);
        mIsShowPic.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                SharedPreferences sp = getSharedPreferences("Setting", MODE_PRIVATE);
                Editor ed = sp.edit();
                ed.putBoolean("isShowPic", isChecked);
                ed.commit();
            }
        });

        mStartScreen = (RelativeLayout) findViewById(R.id.rl_startscreen);
        mStartScreen.setVisibility(View.VISIBLE);
        mCheats = (Button) findViewById(R.id.btn_cheats);
        mCheats.setOnClickListener(this);
        mCategory = (Button) findViewById(R.id.btn_category);
        mCategory.setOnClickListener(this);
        mGame = (Button) findViewById(R.id.btn_game);
        mRecommend = (Button) findViewById(R.id.btn_recommend);
        mSetup = (Button) findViewById(R.id.btn_setup);
        mGame.setOnClickListener(this);

        mRecommend.setOnClickListener(this);
        mSetup.setOnClickListener(this);

        updateMenuStatus(0);
        TextView tip = (TextView) findViewById(R.id.tv_op_tip);
        String[] tips = getResources().getStringArray(R.array.screen_tip);
        Random r = new Random();
        int i = r.nextInt(tips.length);
        tip.setText(tips[i]);
    }

    @Override
    protected void onStart()
    {
        super.onStart();
    }

    @Override
    protected void onResume()
    {
        if (BaseApplication.getInstance().isNeedReloadGameInfo())
        {
            mStartScreen.setVisibility(View.VISIBLE);
            GameManagerUtil.loadPackageInfo(this, null);
            appInitDownLoad();
            BaseApplication.getInstance().setNeedReloadGameInfo(false);
        }
        super.onResume();
    }

    @Override
    protected void onServiceEvent(String id, Object param1, Object param2)
    {
        if (RemoteServerService.RemoteServer_Event_RemoteServer_Success.equals(id))
        {
            if (RemoteServerService.ACTION_GAME_IDENTIFIER.equals(param1))
            {
                isCreate = false;
                DownLoaderUtil du = DownLoaderUtil.getInstence(this);
                du.nextDownload();
                MobclickAgent.onEvent(this, "ShowMain");
                JSONObject data = (JSONObject) param2;
                GameManagerUtil.InitAppData(this, data);
                runOnUiThread(new Runnable()
                {

                    @Override
                    public void run()
                    {
                        mStartScreen.setVisibility(View.INVISIBLE);
                        mGameListAdapter.notifyDataSetChanged();
                        mRecommendListAdapter.notifyDataSetChanged();
                        mCheatsListAdapter.notifyDataSetChanged();

                        mRecommendListView.onRefreshComplete();
                        mRecommendListView.notifyLoadMoreComplet();
                        mRecommendListView.setIsShowLoadMoreFooter(false);

                        mCheatsListView.setIsShowLoadMoreFooter(true);
                        mCheatsListView.onRefreshComplete();
                        mCheatsListView.notifyLoadMoreComplet();

                        if (GameManagerUtil.GameInfos.size() == 0)
                        {
                            mViewPager.setCurrentItem(2);
                            mGameLayout.findViewById(R.id.no_game_hint).setVisibility(View.VISIBLE);
                        } else
                        {
                            mGameLayout.findViewById(R.id.no_game_hint).setVisibility(View.GONE);
                        }

                        createTagsShow();
                        CoverFlow reflectingCoverFlow = (CoverFlow) findViewById(R.id.coverflowReflect);
                        if (GameManagerUtil.MarrowsList.size() > 0)
                        {
                            setupCoverFlow(reflectingCoverFlow);
                            findViewById(R.id.btn_close).setOnClickListener(new OnClickListener()
                            {
                                @Override
                                public void onClick(View v)
                                {
                                    findViewById(R.id.rl_news).setVisibility(View.GONE);
                                    mRia.setResources(null);
                                    mRia.notifyDataSetChanged();
                                }
                            });
                        } else
                        {
                            findViewById(R.id.rl_news).setVisibility(View.GONE);
                        }
                    }
                });
            } else if (RemoteServerService.ACTION_GAME_RANK.equals(param1))
            {
                JSONObject recommends = (JSONObject) param2;
                GameManagerUtil.updateGameRankRecommends(recommends, true);
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mRecommendListView.setIsShowLoadMoreFooter(false);
                        mRecommendListAdapter.notifyDataSetChanged();
                        mRecommendListView.onRefreshComplete();
                        mRecommendListView.notifyLoadMoreComplet();
                    }
                });
            } else if (RemoteServerService.ACTION_GAME_ARTICLES.equals(param1))
            {
                JSONObject articles = (JSONObject) param2;
                GameManagerUtil.updateArticleList(articles, isCheatsClear);
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            mCheatsListAdapter.notifyDataSetChanged();
                            mCheatsListView.onRefreshComplete();
                            mCheatsListView.notifyLoadMoreComplet();
                            boolean hasMore = GameManagerUtil.ArticlesList.size() < GameManagerUtil.ArticlesTotalCount;
                            mCheatsListView.setIsShowLoadMoreFooter(hasMore);
                        }
                        catch (Exception e)
                        {}

                    }
                });
            }
        }
        else if (RemoteServerService.RemoteServer_Event_RemoteServer_Error.equals(id))
        {
            if (RemoteServerService.ACTION_GAME_IDENTIFIER.equals(param1))
            {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        appInitDownLoad();

                                    }
                                }).setMessage("网络不给力啊，是否重试?").setNegativeButton("取消", new DialogInterface.OnClickListener()
                                {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        finish();
                                    }
                                }).create();
                        alertDialog.show();
                    }
                });
            } else
            {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        Toast.makeText(MainActivity.this, "您的网络不给力，请重试一下。", Toast.LENGTH_SHORT).show();
                        mCheatsListView.notifyLoadMoreComplet();
                        mCheatsListView.onRefreshComplete();
                        mRecommendListView.onRefreshComplete();
                    }
                });
            }
        } else if (Activity_Event_Internet_Resource_Download_Success.equals(id))
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mRecommendListAdapter.notifyDataSetChanged();
                    mCheatsListAdapter.notifyDataSetChanged();
                    if (findViewById(R.id.rl_news).getVisibility() == View.VISIBLE)
                    {
                        mRia.notifyDataSetChanged();
                    }
                }
            });

        }
        else if (DownLoaderUtil.Activity_Event_FileDownload_Info.equals(id))
        {
            if (1 == (Integer) param1)
            {
                DownloadEvent event = new DownloadEvent();
                event.id = DownLoaderUtil.Activity_Event_FileDownload_Info;
                event.param1 = (Integer) 1;
                event.param2 = param2;
                JSONObject json = (JSONObject) param2;
                String url = json.optString("url", "");
                mDownloadEvents.put(url, event);
                // checkInstallApk(json);
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mRecommendListAdapter.notifyDataSetChanged();
                    }
                });

            } else if (-1 == (Integer) param1)
            {
                showSDCardError();
            }
            else if (-2 == (Integer) param1)
            {
                showDownloadLongClick(param2);
            }
            else if (0 == (Integer) param1)
            {
                DownloadEvent event = new DownloadEvent();
                event.id = DownLoaderUtil.Activity_Event_FileDownload_Info;
                event.param1 = param1;
                event.param2 = param2;
                String url = (String) param2;
                mDownloadEvents.put(url, event);
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mRecommendListAdapter.notifyDataSetChanged();
                        Toast.makeText(MainActivity.this, "您的网络不给力啊，无法继续下载请调整好了在点我。", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } else if (DownLoaderUtil.Activity_Event_FileDownload_Pause.equals(id))
        {
            String url = (String) param2;
            DownloadEvent event = new DownloadEvent();
            event.id = DownLoaderUtil.Activity_Event_FileDownload_Pause;
            event.param1 = param1;
            event.param2 = param2;
            mDownloadEvents.put(url, event);
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mRecommendListAdapter.notifyDataSetChanged();
                }
            });
        }
        else if (DownLoaderUtil.Activity_Event_FileDownload_Start.equals(id))
        {
            String url = (String) param2;
            DownloadEvent event = new DownloadEvent();
            event.id = DownLoaderUtil.Activity_Event_FileDownload_Start;
            event.param1 = param1;
            event.param2 = param2;
            mDownloadEvents.put(url, event);
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    mRecommendListAdapter.notifyDataSetChanged();
                }
            });
        }

    }

    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        event.setLocation(event.getX() + displayWidth * 0.2f, event.getY());
        mSetupLayout.dispatchTouchEvent(event);
        return true;
    }

    /**
     * Setup cover flow.
     * 
     * @param mCoverFlow
     *            the m cover flow
     * @param reflect
     *            the reflect
     */
    private void setupCoverFlow(final CoverFlow mCoverFlow)
    {
        BaseAdapter coverImageAdapter;

        List<JSONObject> ms = new ArrayList<JSONObject>(GameManagerUtil.MarrowsList);
        String[] resids = new String[ms.size()];
        for (int i = 0; i < ms.size(); i++)
        {
            try
            {
                JSONObject m = ms.get(i);
                String type = m.getString("policy");
                String imageurl = null;
                if ("article".equals(type))
                {
                    imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("articles/data?key=poster&articleref=")
                            .append(m.getInt("ref")).toString();
                } else if ("game".equals(type))
                {
                    imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("games/blob?key=poster&gameref=")
                            .append(m.getInt("ref")).toString();
                }
                String imgpath = internetResourceDownload(imageurl);
                if (imgpath == null)
                {
                    resids[i] = "default";
                } else
                {
                    resids[i] = imgpath;
                }
            }
            catch (JSONException e)
            {
                e.printStackTrace();
                resids[i] = "default";
            }
        }
        mRia = new ResourceImageAdapter(this);
        mRia.setResources(resids);
        coverImageAdapter = new ReflectingImageAdapter(mRia);
        mCoverFlow.setAdapter(coverImageAdapter);
        setupListeners(mCoverFlow);
        mCoverFlow.setSelection(0, true);
    }

    private ResourceImageAdapter mRia;

    /**
     * Sets the up listeners.
     * 
     * @param mCoverFlow
     *            the new up listeners
     */
    private void setupListeners(final CoverFlow mCoverFlow)
    {
        mCoverFlow.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id)
            {
                JSONObject m = GameManagerUtil.MarrowsList.get(position);
                try
                {
                    String type = m.getString("policy");

                    if ("article".equals(type))
                    {
                        String content = m.getString("content");
                        Intent intent = new Intent(MainActivity.this, ArticleActivity.class);
                        intent.putExtra("PackageName", m.getString("identifier"));
                        JSONObject article = new JSONObject();
                        article.put("content", content);
                        JSONArray articles = new JSONArray();
                        articles.put(article);
                        intent.putExtra("Articles", articles.toString());
                        intent.putExtra("Index", 0);
                        startActivity(intent);
                    } else if ("game".equals(type))
                    {
                        Intent intent = new Intent(MainActivity.this, GameDetailActivity.class);
                        int gameref = m.getInt("ref");
                        intent.putExtra("gameref", gameref);
                        if (m.has("identifier"))
                        {
                            String identifier = m.getString("identifier");
                            intent.putExtra("packageName", identifier);
                            startActivity(intent);
                        }
                    }

                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }

        });
        mCoverFlow.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(final AdapterView<?> parent, final View view, final int position, final long id)
            {
                JSONObject m = GameManagerUtil.MarrowsList.get(position);
                TextView text = (TextView) findViewById(R.id.tv_coverflow_text);
                try
                {
                    String title = m.getString("title");
                    text.setText(title);
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                    text.setText("");

                }
            }

            @Override
            public void onNothingSelected(final AdapterView<?> parent)
            {
                // textView.setText("Nothing clicked!");
            }
        });
    }

    public void startActivity(int type)
    {
        switch (type)
        {
            case ACTIVITY_TYPE_SUGGESTION:
            {
                Intent in = new Intent(this, SuggestionActiviy.class);
                startActivity(in);
                break;
            }
            case ACTIVITY_TYPE_ABOUT_APP:
            {
                Intent in = new Intent(this, AboutAppActivity.class);
                startActivity(in);
                break;
            }
            case ACTIVITY_TYPE_HELP:
            {
                Intent in = new Intent(this, HelpActivity.class);
                startActivity(in);
                break;
            }
            default:
            {
                break;
            }
        }
    }

    private void showClearDailog()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                mDownloadEvents.clear();
                                DownLoaderUtil.getInstence(MainActivity.this).clearAllDownLoader();
                                if (InternetResourceCache.delCacheDir())
                                {
                                    Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                                    mCheatsListAdapter.notifyDataSetChanged();
                                    mRecommendListAdapter.notifyDataSetChanged();
                                }
                                mRecommendListAdapter.notifyDataSetChanged();
                            }
                        }).setMessage("是否停止所有下载，并删除下载缓存?").setNegativeButton("取消", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.cancel();
                            }
                        }).create();
                alertDialog.show();
            }
        });
    }

    /**
     * type:0 - game;1:recommend; 2-setup
     * 
     * @param type
     */
    public void updateMenuStatus(int type)
    {
        switch (type)
        {
            case 0:
            {
                mGame.setBackgroundResource(R.drawable.mainmenubar_pressed_background);
                mCheats.setBackgroundColor(0x00000000);
                mRecommend.setBackgroundColor(0x00000000);
                mCategory.setBackgroundColor(0x00000000);
                break;
            }
            case 1:
            {

                mGame.setBackgroundResource(0x00000000);
                mCheats.setBackgroundResource(R.drawable.mainmenubar_pressed_background);
                mRecommend.setBackgroundColor(0x00000000);
                mCategory.setBackgroundColor(0x00000000);
                break;
            }
            case 2:
            {

                mGame.setBackgroundResource(0x00000000);
                mCheats.setBackgroundColor(0x00000000);
                mRecommend.setBackgroundResource(R.drawable.mainmenubar_pressed_background);
                mCategory.setBackgroundColor(0x00000000);
                break;
            }
            default:
            {
                mGame.setBackgroundResource(0x00000000);
                mCheats.setBackgroundColor(0x00000000);
                mRecommend.setBackgroundColor(0x00000000);
                mCategory.setBackgroundResource(R.drawable.mainmenubar_pressed_background);
                break;
            }
        }
    }

    @Override
    public void onBackPressed()
    {
        View news = findViewById(R.id.rl_news);
        if (news.getVisibility() == View.VISIBLE)
        {
            news.setVisibility(View.GONE);
        } else
        {
            super.onBackPressed();
        }
    }

    private int converToPx(int dp)
    {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

    private void showSDCardError()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.cancel();
                            }
                        }).setMessage("您手机未安装SD，请安装后在使用下载功能。").create();
                alertDialog.show();
            }
        });
    }

    private void showDownloadLongClick(Object param2)
    {
        final Object p2 = param2;
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
                alertDialog.setTitle("菜单");
                alertDialog.setItems
                        (
                                R.array.downloadmenu, new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        DownLoadButton dlBut = (DownLoadButton) p2;
                                        switch (which)
                                        {
                                            case 0:
                                            {
                                                dlBut.installAPK();
                                                break;
                                            }
                                            case 1:
                                            {
                                                dlBut.deleteDownLoadFile();
                                                break;
                                            }
                                        }
                                    }
                                }
                        );
                alertDialog.show();

            }
        });
    }

    public int getCurrentPageIndex()
    {
        return mViewPager.getCurrentItem();
    }

}
